<template>
    <view>
        <view class="container">
            <swiper class="goodsimgs" :indicator-dots="true" :autoplay="true" interval="3000" duration="1000">
                <swiper-item v-for="(item, index) in goods.gallery" :key="index">
                    <image :src="item" background-size="cover"></image>
                </swiper-item>
            </swiper>
            <!-- 分享 -->
            <view class="goods_name">
                <view class="goods_name_left">{{ goods.name }}</view>
                <view v-if="canShare" class="goods_name_right" @tap="shareFriendOrCircle">分享</view>
            </view>
            <view class="share-pop-box" v-if="openShare">
                <view class="share-pop">
                    <view class="close" @tap="closeShare">
                        <van-icon class="icon" name="cross" />
                    </view>
                    <view class="share-info">
                        <button class="sharebtn" open-type="share" v-if="!isGroupon">
                            <image class="sharebtn_image" src="/static/images/wechat.png"></image>
                            <view class="sharebtn_text">分享给好友</view>
                        </button>
                        <button class="savesharebtn" open-type="openSetting" @opensetting="handleSetting" v-if="!isGroupon && !canWrite">
                            <image class="sharebtn_image" src="/static/images/friend.png"></image>
                            <view class="sharebtn_text">生成海报</view>
                        </button>
                        <button class="savesharebtn" @tap="saveShare" v-if="!isGroupon && canWrite">
                            <image class="sharebtn_image" src="/static/images/friend.png"></image>
                            <view class="sharebtn_text">生成海报</view>
                        </button>
                    </view>
                </view>
            </view>

            <view class="goods-info">
                <view class="c">
                    <text class="desc">{{ goods.brief }}</text>
                    <view class="price">
                        <view class="counterPrice">原价：￥{{ goods.counterPrice }}</view>
                        <view class="retailPrice">现价：￥{{ checkedSpecPrice }}</view>
                    </view>

                    <view class="brand" v-if="brand.name">
                        <navigator :url="'../brandDetail/brandDetail?id=' + brand.id">
                            <text>{{ brand.name }}</text>
                        </navigator>
                    </view>
                </view>
            </view>
            <view class="section-nav section-attr" @tap="switchAttrPop">
                <view class="t">{{ checkedSpecText }}</view>
                <van-icon class="i" name="arrow" />
            </view>
            <view class="comments" v-if="comment.count > 0">
                <view class="h">
                    <navigator :url="'/pages/comment/comment?valueId=' + goods.id + '&type=0'">
                        <text class="t">评价({{ comment.count > 999 ? '999+' : comment.count }})</text>
                        <view class="i">
                            查看全部
                            <van-icon name="arrow" />
                        </view>
                    </navigator>
                </view>
                <view class="b">
                    <view class="item" v-for="(item, index) in comment.data" :key="item.id">
                        <view class="info">
                            <view class="user">
                                <image :src="item.avatar"></image>
                                <text>{{ item.nickname }}</text>
                            </view>
                            <view class="time">{{ item.addTime }}</view>
                        </view>

                        <view class="content">
                            {{ item.content }}
                        </view>

                        <view class="imgs" v-if="item.picList.length > 0">
                            <image class="img" :src="iitem + ' '" v-for="(iitem, index1) in item.picList" :key="index1"></image>
                        </view>

                        <view class="customer-service" v-if="item.adminContent">
                            <text class="u">商家回复：</text>
                            <text class="c">{{ item.adminContent }}</text>
                        </view>
                    </view>
                </view>
            </view>
            <view class="goods-attr">
                <view class="t">商品参数</view>
                <view class="l">
                    <view class="item" v-for="(item, index) in attribute" :key="item.name">
                        <text class="left">{{ item.attribute }}</text>

                        <text class="right">{{ item.value }}</text>
                    </view>
                </view>
            </view>

            <view class="detail">
                <!-- <template is="wxParse" :data="wxParseData:goodsDetail.nodes"/> -->
                <mp-html :content="article_goodsDetail"></mp-html>
            </view>

            <view class="common-problem">
                <view class="h">
                    <view class="line"></view>
                    <text class="title">常见问题</text>
                </view>
                <view class="b">
                    <view class="item" v-for="(item, index) in issueList" :key="item.id">
                        <view class="question-box">
                            <text class="spot"></text>
                            <text class="question">{{ item.question }}</text>
                        </view>

                        <view class="answer">
                            {{ item.answer }}
                        </view>
                    </view>
                </view>
            </view>

            <!-- 大家都在看 -->
            <view class="related-goods" v-if="relatedGoods.length > 0">
                <view class="h">
                    <view class="line"></view>
                    <text class="title">大家都在看</text>
                </view>
                <view class="b">
                    <view class="item" v-for="(item, index) in relatedGoods" :key="item.id">
                        <navigator :url="'/pages/goods/goods?id=' + item.id">
                            <image class="img" :src="item.picUrl" background-size="cover"></image>
                            <text class="name">{{ item.name }}</text>
                            <text class="price">￥{{ item.retailPrice }}</text>
                        </navigator>
                    </view>
                </view>
            </view>
        </view>
        <!-- 规格选择界面 -->
        <view class="attr-pop-box" v-if="openAttr">
            <view class="attr-pop">
                <view class="close" @tap="closeAttr">
                    <van-icon class="icon" name="cross" />
                </view>
                <view class="img-info">
                    <image class="img" :src="tmpPicUrl"></image>
                    <view class="info">
                        <view class="c">
                            <view class="p">价格：￥{{ checkedSpecPrice }}</view>
                            <view class="a">{{ tmpSpecText }}</view>
                        </view>
                    </view>
                </view>

                <!-- 规格列表 -->
                <view class="spec-con">
                    <view class="spec-item" v-for="(item, index) in specificationList" :key="item.name">
                        <view class="name">{{ item.name }}</view>

                        <view class="values">
                            <view
                                :class="'value ' + (vitem.checked ? 'selected' : '')"
                                @tap="clickSkuValue"
                                :data-value-id="vitem.id"
                                :data-name="vitem.specification"
                                v-for="(vitem, index1) in item.valueList"
                                :key="vitem.id"
                            >
                                {{ vitem.value }}
                            </view>
                        </view>
                    </view>

                    <view class="spec-item" v-if="groupon.length > 0">
                        <view class="name">团购立减</view>
                        <view class="values">
                            <view
                                :class="'value ' + (vitem.checked ? 'selected' : '')"
                                @tap="clickGroupon"
                                :data-value-id="vitem.id"
                                :data-name="vitem.specification"
                                v-for="(vitem, index) in groupon"
                                :key="vitem.id"
                            >
                                ￥{{ vitem.discount }} ({{ vitem.discountMember }}人)
                            </view>
                        </view>
                    </view>

                    <!-- 数量 -->
                    <view class="number-item">
                        <view class="name">数量</view>
                        <view class="selnum">
                            <view class="cut" @tap="cutNumber">-</view>
                            <input :value="number" class="number" :disabled="true" type="number" />
                            <view class="add" @tap="addNumber">+</view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 联系客服 -->
        <view class="contact">
            <contact-button style="opacity: 0; position: absolute" type="default-dark" session-from="weapp" size="27"></contact-button>
        </view>

        <!-- 底部按钮 -->
        <view class="bottom-btn">
            <view class="l l-collect" @tap="addCollectOrNot" v-if="!isGroupon">
                <van-icon class="icon" name="star" color="#ab956d" v-if="collect" />
                <van-icon class="icon" name="star-o" v-else />
            </view>
            <view class="l l-cart" v-if="!isGroupon">
                <view class="box">
                    <text class="cart-count">{{ cartGoodsCount }}</text>
                    <van-icon @tap.native="openCartPage" class="icon" name="cart-o" />
                </view>
            </view>
            <view class="r" @tap="addToCart" v-if="!isGroupon">加入购物车</view>
            <view class="c" @tap="addFast" v-if="!soldout">{{ isGroupon ? '参加团购' : '立即购买' }}</view>
            <view class="n" v-if="soldout">商品已售空</view>
        </view>
    </view>
</template>

<script>
var app = getApp();

var undefined;

var util = require('../../utils/util.js');

var api = require('../../config/api.js');

var user = require('../../utils/user.js');

export default {
    data() {
        return {
            canShare: false,
            id: 0,

            goods: {
                gallery: [],
                name: '',
                brief: '',
                counterPrice: '',
                id: ''
            },

            groupon: [],

            //该商品支持的团购规格
            grouponLink: {},

            //参与的团购
            attribute: [],

            issueList: [],
            comment: [],

            brand: {
                name: '',
                id: ''
            },

            specificationList: [],
            productList: [],
            relatedGoods: [],
            cartGoodsCount: 0,
            userHasCollect: 0,
            number: 1,
            tmpPicUrl: '',
            checkedSpecText: '规格数量选择',
            tmpSpecText: '请选择规格数量',
            checkedSpecPrice: 0,
            openAttr: false,
            openShare: false,
            collect: false,
            shareImage: '',
            isGroupon: false,

            //标识是否是一个参团购买
            soldout: false,

            //用户是否获取了保存相册的权限
            canWrite: false,

            iitem: '',
            article_goodsDetail: '',

            vitem: {
                checked: false,
                id: '',
                specification: '',
                value: '',
                discount: '',
                discountMember: ''
            }
        };
    }, // 页面分享
    onShareAppMessage: function () {
        let that = this;
        return {
            title: that.goods.name,
            desc: '唯爱与美食不可辜负',
            path: '/pages/index/index?goodId=' + this.id
        };
    },
    onLoad: function (options) {
        // 页面初始化 options为页面跳转所带来的参数
        if (options.id) {
            this.setData({
                id: parseInt(options.id)
            });
            this.getGoodsInfo();
        }

        if (options.grouponId) {
            this.setData({
                isGroupon: true
            });
            this.getGrouponInfo(options.grouponId);
        }

        let that = this;
        uni.getSetting({
            success: function (res) {
                console.log(res); //不存在相册授权

                if (!res.authSetting['scope.writePhotosAlbum']) {
                    uni.authorize({
                        scope: 'scope.writePhotosAlbum',
                        success: function () {
                            that.setData({
                                canWrite: true
                            });
                        },
                        fail: function (err) {
                            that.setData({
                                canWrite: false
                            });
                        }
                    });
                } else {
                    that.setData({
                        canWrite: true
                    });
                }
            }
        });
    },
    onShow: function () {
        // 页面显示
        var that = this;
        util.request(api.CartGoodsCount).then(function (res) {
            if (res.errno === 0) {
                that.setData({
                    cartGoodsCount: res.data
                });
            }
        });
    },
    onHide: function () {
        // 页面隐藏
    },
    onUnload: function () {
        // 页面关闭
    },
    onReady: function () {
        // 页面渲染完成
    },
    methods: {
        shareFriendOrCircle: function () {
            //var that = this;
            if (this.openShare === false) {
                this.setData({
                    openShare: !this.openShare
                });
            } else {
                return false;
            }
        },

        handleSetting: function (e) {
            var that = this; // console.log(e)

            if (!e.detail.authSetting['scope.writePhotosAlbum']) {
                uni.showModal({
                    title: '警告',
                    content: '不授权无法保存',
                    showCancel: false
                });
                that.setData({
                    canWrite: false
                });
            } else {
                uni.showToast({
                    title: '保存成功'
                });
                that.setData({
                    canWrite: true
                });
            }
        },

        // 保存分享图
        saveShare: function () {
            let that = this;
            uni.downloadFile({
                url: that.shareImage,
                success: function (res) {
                    console.log(res);
                    uni.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: function (res) {
                            uni.showModal({
                                title: '生成海报成功',
                                content: '海报已成功保存到相册，可以分享到朋友圈了',
                                showCancel: false,
                                confirmText: '好的',
                                confirmColor: '#a78845',
                                success: function (res) {
                                    if (res.confirm) {
                                        console.log('用户点击确定');
                                    }
                                }
                            });
                        },
                        fail: function (res) {
                            console.log('fail');
                        }
                    });
                },
                fail: function () {
                    console.log('fail');
                }
            });
        },

        //从分享的团购进入
        getGrouponInfo: function (grouponId) {
            let that = this;
            util.request(api.GroupOnJoin, {
                grouponId: grouponId
            }).then(function (res) {
                if (res.errno === 0) {
                    that.setData({
                        grouponLink: res.data.groupon,
                        id: res.data.goods.id
                    }); //获取商品详情

                    that.getGoodsInfo();
                }
            });
        },

        // 获取商品信息
        getGoodsInfo: function () {
            let that = this;
            util.request(api.GoodsDetail, {
                id: that.id
            }).then(function (res) {
                if (res.errno === 0) {
                    let _specificationList = res.data.specificationList;
                    let _tmpPicUrl = res.data.productList[0].url; //console.log("pic: "+_tmpPicUrl);
                    // 如果仅仅存在一种货品，那么商品页面初始化时默认checked

                    if (_specificationList.length == 1) {
                        if (_specificationList[0].valueList.length == 1) {
                            _specificationList[0].valueList[0].checked = true; // 如果仅仅存在一种货品，那么商品价格应该和货品价格一致
                            // 这里检测一下

                            let _productPrice = res.data.productList[0].price;
                            let _goodsPrice = res.data.info.retailPrice;

                            if (_productPrice != _goodsPrice) {
                                console.error('商品数量价格和货品不一致');
                            }

                            that.setData({
                                checkedSpecText: _specificationList[0].valueList[0].value,
                                tmpSpecText: '已选择：' + _specificationList[0].valueList[0].value
                            });
                        }
                    }

                    that.setData({
                        goods: res.data.info,
                        attribute: res.data.attribute,
                        issueList: res.data.issue,
                        comment: res.data.comment,
                        brand: res.data.brand,
                        specificationList: res.data.specificationList,
                        productList: res.data.productList,
                        userHasCollect: res.data.userHasCollect,
                        shareImage: res.data.shareImage,
                        checkedSpecPrice: res.data.info.retailPrice,
                        groupon: res.data.groupon,
                        canShare: res.data.share,
                        //选择规格时，默认展示第一张图片
                        tmpPicUrl: _tmpPicUrl
                    }); //如果是通过分享的团购参加团购，则团购项目应该与分享的一致并且不可更改

                    if (that.isGroupon) {
                        let groupons = that.groupon;

                        for (var i = 0; i < groupons.length; i++) {
                            if (groupons[i].id != that.grouponLink.rulesId) {
                                groupons.splice(i, 1);
                            }
                        }

                        groupons[0].checked = true; //重设团购规格

                        that.setData({
                            groupon: groupons
                        });
                    }

                    if (res.data.userHasCollect == 1) {
                        that.setData({
                            collect: true
                        });
                    } else {
                        that.setData({
                            collect: false
                        });
                    }

                    //WxParse.wxParse('goodsDetail', 'html', res.data.info.detail, that)
                    that.article_goodsDetail = that.escape2Html(res.data.info.detail); //获取推荐商品

                    that.getGoodsRelated();
                }
            });
        },

        // 获取推荐商品
        getGoodsRelated: function () {
            let that = this;
            util.request(api.GoodsRelated, {
                id: that.id
            }).then(function (res) {
                if (res.errno === 0) {
                    that.setData({
                        relatedGoods: res.data.list
                    });
                }
            });
        },

        // 团购选择
        clickGroupon: function (event) {
            let that = this; //参与团购，不可更改选择

            if (that.isGroupon) {
                return;
            }

            let specName = event.currentTarget.dataset.name;
            let specValueId = event.currentTarget.dataset.valueId;
            let _grouponList = this.groupon;

            for (let i = 0; i < _grouponList.length; i++) {
                if (_grouponList[i].id == specValueId) {
                    if (_grouponList[i].checked) {
                        _grouponList[i].checked = false;
                    } else {
                        _grouponList[i].checked = true;
                    }
                } else {
                    _grouponList[i].checked = false;
                }
            }

            this.setData({
                groupon: _grouponList
            });
        },

        // 规格选择
        clickSkuValue: function (event) {
            let that = this;
            let specName = event.currentTarget.dataset.name;
            let specValueId = event.currentTarget.dataset.valueId; //判断是否可以点击
            //TODO 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环

            let _specificationList = this.specificationList;

            for (let i = 0; i < _specificationList.length; i++) {
                if (_specificationList[i].name === specName) {
                    for (let j = 0; j < _specificationList[i].valueList.length; j++) {
                        if (_specificationList[i].valueList[j].id == specValueId) {
                            //如果已经选中，则反选
                            if (_specificationList[i].valueList[j].checked) {
                                _specificationList[i].valueList[j].checked = false;
                            } else {
                                _specificationList[i].valueList[j].checked = true;
                            }
                        } else {
                            _specificationList[i].valueList[j].checked = false;
                        }
                    }
                }
            }

            this.setData({
                specificationList: _specificationList
            }); //重新计算spec改变后的信息

            this.changeSpecInfo(); //重新计算哪些值不可以点击
        },

        //获取选中的团购信息
        getCheckedGrouponValue: function () {
            let checkedValues = {};
            let _grouponList = this.groupon;

            for (let i = 0; i < _grouponList.length; i++) {
                if (_grouponList[i].checked) {
                    checkedValues = _grouponList[i];
                }
            }

            return checkedValues;
        },

        //获取选中的规格信息
        getCheckedSpecValue: function () {
            let checkedValues = [];
            let _specificationList = this.specificationList;

            for (let i = 0; i < _specificationList.length; i++) {
                let _checkedObj = {
                    name: _specificationList[i].name,
                    valueId: 0,
                    valueText: ''
                };

                for (let j = 0; j < _specificationList[i].valueList.length; j++) {
                    if (_specificationList[i].valueList[j].checked) {
                        _checkedObj.valueId = _specificationList[i].valueList[j].id;
                        _checkedObj.valueText = _specificationList[i].valueList[j].value;
                    }
                }

                checkedValues.push(_checkedObj);
            }

            return checkedValues;
        },

        //判断规格是否选择完整
        isCheckedAllSpec: function () {
            return !this.getCheckedSpecValue().some(function (v) {
                if (v.valueId == 0) {
                    return true;
                }
            });
        },

        getCheckedSpecKey: function () {
            let checkedValue = this.getCheckedSpecValue().map(function (v) {
                return v.valueText;
            });
            return checkedValue;
        },

        // 规格改变时，重新计算价格及显示信息
        changeSpecInfo: function () {
            let checkedNameValue = this.getCheckedSpecValue(); //设置选择的信息

            let checkedValue = checkedNameValue
                .filter(function (v) {
                    if (v.valueId != 0) {
                        return true;
                    } else {
                        return false;
                    }
                })
                .map(function (v) {
                    return v.valueText;
                });

            if (checkedValue.length > 0) {
                this.setData({
                    tmpSpecText: checkedValue.join('　')
                });
            } else {
                this.setData({
                    tmpSpecText: '请选择规格数量'
                });
            }

            if (this.isCheckedAllSpec()) {
                this.setData({
                    checkedSpecText: this.tmpSpecText
                }); // 规格所对应的货品选择以后

                let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());

                if (!checkedProductArray || checkedProductArray.length <= 0) {
                    this.setData({
                        soldout: true
                    });
                    console.error('规格所对应货品不存在');
                    return;
                }

                let checkedProduct = checkedProductArray[0]; //console.log("checkedProduct: "+checkedProduct.url);

                if (checkedProduct.number > 0) {
                    this.setData({
                        checkedSpecPrice: checkedProduct.price,
                        tmpPicUrl: checkedProduct.url,
                        soldout: false
                    });
                } else {
                    this.setData({
                        checkedSpecPrice: this.goods.retailPrice,
                        soldout: true
                    });
                }
            } else {
                this.setData({
                    checkedSpecText: '规格数量选择',
                    checkedSpecPrice: this.goods.retailPrice,
                    soldout: false
                });
            }
        },

        // 获取选中的产品（根据规格）
        getCheckedProductItem: function (key) {
            return this.productList.filter(function (v) {
                if (v.specifications.toString() == key.toString()) {
                    return true;
                } else {
                    return false;
                }
            });
        },

        //添加或是取消收藏
        addCollectOrNot: function () {
            let that = this;
            util.request(
                api.CollectAddOrDelete,
                {
                    type: 0,
                    valueId: this.id
                },
                'POST'
            ).then(function (res) {
                if (that.userHasCollect == 1) {
                    that.setData({
                        collect: false,
                        userHasCollect: 0
                    });
                } else {
                    that.setData({
                        collect: true,
                        userHasCollect: 1
                    });
                }
            });
        },

        //立即购买（先自动加入购物车）
        addFast: function () {
            var that = this;

            if (this.openAttr == false) {
                //打开规格选择窗口
                this.setData({
                    openAttr: !this.openAttr
                });
            } else {
                //提示选择完整规格
                if (!this.isCheckedAllSpec()) {
                    util.showErrorToast('请选择完整规格');
                    return false;
                } //根据选中的规格，判断是否有对应的sku信息

                let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());

                if (!checkedProductArray || checkedProductArray.length <= 0) {
                    //找不到对应的product信息，提示没有库存
                    util.showErrorToast('没有库存');
                    return false;
                }

                let checkedProduct = checkedProductArray[0]; //验证库存

                if (checkedProduct.number <= 0) {
                    util.showErrorToast('没有库存');
                    return false;
                } //验证团购是否有效

                let checkedGroupon = this.getCheckedGrouponValue(); //立即购买

                util.request(
                    api.CartFastAdd,
                    {
                        goodsId: this.goods.id,
                        number: this.number,
                        productId: checkedProduct.id
                    },
                    'POST'
                ).then(function (res) {
                    if (res.errno == 0) {
                        // 如果storage中设置了cartId，则是立即购买，否则是购物车购买
                        try {
                            uni.setStorageSync('cartId', res.data);
                            uni.setStorageSync('grouponRulesId', checkedGroupon.id);
                            uni.setStorageSync('grouponLinkId', that.grouponLink.id);
                            uni.navigateTo({
                                url: '/pages/checkout/checkout'
                            });
                        } catch (e) {}
                    } else {
                        util.showErrorToast(res.errmsg);
                    }
                });
            }
        },

        //添加到购物车
        addToCart: function () {
            var that = this;

            if (this.openAttr == false) {
                //打开规格选择窗口
                this.setData({
                    openAttr: !this.openAttr
                });
            } else {
                //提示选择完整规格
                if (!this.isCheckedAllSpec()) {
                    util.showErrorToast('请选择完整规格');
                    return false;
                } //根据选中的规格，判断是否有对应的sku信息

                let checkedProductArray = this.getCheckedProductItem(this.getCheckedSpecKey());

                if (!checkedProductArray || checkedProductArray.length <= 0) {
                    //找不到对应的product信息，提示没有库存
                    util.showErrorToast('没有库存');
                    return false;
                }

                let checkedProduct = checkedProductArray[0]; //验证库存

                if (checkedProduct.number <= 0) {
                    util.showErrorToast('没有库存');
                    return false;
                } //添加到购物车

                util.request(
                    api.CartAdd,
                    {
                        goodsId: this.goods.id,
                        number: this.number,
                        productId: checkedProduct.id
                    },
                    'POST'
                ).then(function (res) {
                    let _res = res;

                    if (_res.errno == 0) {
                        uni.showToast({
                            title: '添加成功'
                        });
                        that.setData({
                            openAttr: !that.openAttr,
                            cartGoodsCount: _res.data
                        });

                        if (that.userHasCollect == 1) {
                            that.setData({
                                collect: true
                            });
                        } else {
                            that.setData({
                                collect: false
                            });
                        }
                    } else {
                        util.showErrorToast(_res.errmsg);
                    }
                });
            }
        },

        cutNumber: function () {
            this.setData({
                number: this.number - 1 > 1 ? this.number - 1 : 1
            });
        },

        addNumber: function () {
            this.setData({
                number: this.number + 1
            });
        },

        switchAttrPop: function () {
            if (this.openAttr == false) {
                this.setData({
                    openAttr: !this.openAttr
                });
            }
        },

        closeAttr: function () {
            this.setData({
                openAttr: false
            });
        },

        closeShare: function () {
            this.setData({
                openShare: false
            });
        },

        openCartPage: function () {
            uni.switchTab({
                url: '/pages/cart/cart'
            });
        }
    }
};
</script>
<style>
@import './goods.css';
</style>
